<template>
  <div class="carousel-container">
    <el-card shadow="never" class="carousel-list">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="success" @click="openDialog('insert', null)">
              <i-ep-plus />新增轮播图
            </el-button>
            <el-button
              type="danger"
              :disabled="itemTotal === 0"
              @click="deleteCarousel(null)"
            >
              <i-ep-delete />删除轮播图
            </el-button>
          </div>
        </div>
      </template>
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="关键字" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="图片名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="全部"
              clearable
              class="!w-[100px]"
              @keyup.enter="handleQuery"
            >
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateTimeRange"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD hh:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery()"
              ><i-ep-search />搜索</el-button
            >
            <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        v-loading="loading"
        :data="carouselList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <!--        <el-table-column-->
        <!--          key="id"-->
        <!--          label="编号"-->
        <!--          align="center"-->
        <!--          prop="id"-->
        <!--          width="100"-->
        <!--        />-->
        <el-table-column label="名称" align="center" prop="title" />
        <el-table-column label="图片" align="center" prop="imageUrl">
          <template #default="scope">
            <img
              :src="scope.row.imageUrl"
              alt="图片"
              style="width: 150px; height: 150px"
            />
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createdUser" />
        <el-table-column label="创建时间" align="center" prop="createdTime" />
        <el-table-column label="修改人" align="center" prop="modifiedUser" />
        <el-table-column label="修改时间" align="center" prop="modifiedTime" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog('edit', scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteCarousel(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="itemTotal > 0"
        v-model:total="itemTotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="图片" prop="imageUrl">
          <single-upload v-model="formData.imageUrl" />
        </el-form-item>
        <el-form-item label="图片名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入图片名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div
          class="dialog-footer"
          style="display: flex; align-items: center; justify-content: center"
        >
          <el-button type="primary" @click="handleSubmit()">确 定</el-button>
          <el-button @click="closeDialog()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import {
  deleteCarousels,
  editCarousel,
  insertCarousel,
  queryCarousel,
  queryCarouselById,
} from "@/api/carousel/index.ts";

const formRef = ref(null);
const carouselList = ref([]);
const loading = ref(false);
const queryFormRef = ref(null);
const itemTotal = ref(0);
const queryParams = reactive({
  title: "",
  status: "",
  pageNum: 1,
  pageSize: 10,
});
const dateTimeRange = ref([]);
const dialog = reactive({
  visible: false,
  title: "",
  width: "50%",
  type: "",
});
const formData = reactive({
  id: "",
  imageUrl: "",
  title: "",
  status: "", // 默认启用
});

// 表单验证规则
const rules = {
  imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
  title: [{ required: true, message: "请输入图片名称", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
};

const deleteCarousel = (id) => {
  // console.log("deleteCarousel", ids.value);
  // 如果id为null，表示批量删除
  if (id === null) {
    if (ids.value.length === 0) {
      ElMessage.warning("请选择要删除的数据");
      return;
    }
    // 批量删除
    ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deleteCarousels(ids.value).then((res) => {
          ElMessage.success("批量删除轮播图成功");
          // 查询
          handleQuery();
        });
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
  } else {
    // 删除
    ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        deleteCarousels([id]).then((res) => {
          ElMessage.success("删除轮播图成功");
          // 查询
          handleQuery();
        });
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
  }
};

const openDialog = (type, id) => {
  // 打开弹窗
  dialog.visible = true;
  // 设置弹窗类型
  dialog.type = type;
  // 设置弹窗标题
  dialog.title = id ? "编辑轮播图" : "新增轮播图";
  // 如果是编辑，根据id查询数据
  if (id) {
    // 根据id查询数据
    queryCarouselById(id).then((res) => {
      // 设置表单数据
      formData.id = res.data.id;
      formData.imageUrl = res.data.imageUrl;
      formData.title = res.data.title;
      formData.status = res.data.status;
    });
  } else {
    // 新增
    // 重置表单
    formRef.value.resetFields();
  }
};

// 关闭弹窗
const closeDialog = () => {
  // 关闭弹窗
  dialog.visible = false;
  // 重置表单
  formRef.value.resetFields();
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    // 判断是否通过验证
    if (valid) {
      // 判断是新增还是编辑
      if (dialog.type === "insert") {
        // 新增
        // console.log("formData", formData);
        // 提交表单
        insertCarousel(formData).then((res) => {
          ElMessage.success("新增轮播图成功");
          // 关闭弹窗
          closeDialog(formRef);
          // 查询
          handleQuery();
        });
        // 关闭弹窗
        closeDialog(formRef);
      }
      if (dialog.type === "edit") {
        // 编辑
        // console.log("formData", formData);
        // 提交表单
        editCarousel(formData).then((res) => {
          ElMessage.success("修改轮播图成功");
          // 关闭弹窗
          closeDialog(formRef);
          // 查询
          handleQuery();
        });
      }
    }
  });
};

// 查询轮播图列表
const handleQuery = () => {
  // console.log("handleQuery");
  // 构造参数
  const params = {
    ...queryParams,
    startTime: dateTimeRange.value[0],
    endTime: dateTimeRange.value[1],
  };
  // console.log("查询参数", params);
  // 查询轮播图列表
  queryCarousel(params).then(({ data }) => {
    carouselList.value = data.list;
    itemTotal.value = data.total;
  });
  console.log("carouselList", carouselList.value);
};

// 删除轮播图
const resetQuery = () => {
  // console.log("resetQuery");
  queryFormRef.value.resetFields();
  dateTimeRange.value[0] = "";
  dateTimeRange.value[1] = "";
  queryParams.pageNum = 1;
  queryParams.title = undefined;
  queryParams.status = undefined;
  handleQuery();
};

// 选中的ids
const ids = ref([]);

// 得到选中的数据
const handleSelectionChange = (val) => {
  // console.log("handleSelectionChange", val);
  ids.value = val.map((item) => item.id);
  console.log("ids", ids.value);
};
onMounted(() => {
  // 查询
  handleQuery();
});
</script>

<style scoped></style>
